<template>
	<view class="">
		<cu-custom :isBack="true">
			<block #content>管理设备</block>
		</cu-custom>

		<view class="bg-white" style="position:fixed;top:178rpx;z-index:10000;width:100vw;">
			<view class="margin-lr-xl margin-top-xl margin-bottom">
				<view class="common-shadow padding flex justify-between align-center">
					<view class="text-df flex justify-start align-center">
						<view class="text-black  text-bold">项目组名称</view>
						<input class="margin-left text-gray" type="text" v-model="projectName" :focus="focus">
					</view>
					<!-- @tap="changeFocus" -->
					<view class="text-gray" @tap="updateInsecticidalLampProject">
						<text class="cuIcon-edit"></text>
					</view>
				</view>
			</view>
			<view>
				<view class="padding-lr-xl flex justify-between align-center padding-bottom-sm">
					<view class="flex justify-start align-center text-black text-bold text-df ">
						<view>直连设备</view>
						<view class="margin-left-sm">
							(共{{total}}个设备)
						</view>
					</view>
					<view class="margin-left-sm text-red-color text-bold text-df" @tap="goToAddDevice(projectId)">
						添加设备
						<text class="cuIcon-right"></text>
					</view>
				</view>
			</view>
		</view>

		<mescroll-body ref="mescrollRef" @init="mescrollInit" :down="downOption" @down="downCallback" :up="upOption"
			@up="getDeviceList" :safearea="true" offset="10" style="position:relative;top:420rpx;z-index:1;width:100%;">
			<view v-for="(item,index) in deviceList" :key="index">
				<view v-for="(subItem,subIndex) in item" :key="subIndex"
					class="common-shadow margin-top-sm margin-bottom-lg margin-lr-xl padding bg-white"
					style="border-radius:15rpx;" @tap="deviceInfo(subItem)">
					<view class="flex justify-between align-center padding-bottom-xs text-df">
						<view class="text-black text-bold text-sm">设备{{subIndex+1}}</view>
						<view class="cuIcon-close" style="font-size: 36rpx;" @tap.stop="remProjectDevice(subItem)" ></view>
					</view>
					<view class="flex justify-between align-center">
						<view class="flex justify-start align-center">
							<img style="width:80rpx;height:auto" src="../../assets/images/device.png" alt=""
								mode="widthFix">
							<view class="padding-left">
								<view class="text-df text-black text-bold text-title">{{subItem.deviceName}}</view>
								<view class="text-xs text-gray-color margin-top-xs">{{subItem.code}}</view>
								<view class="text-xs text-gray-color address-input">{{subItem.address}}</view>
							</view>
						</view>
						<view class="text-center">
							<view class="flex justify-start align-center">
								<signal id="signal" :netSignal="subItem.signal" :inline="subItem.inline"></signal>
								<surplus id="surplus" :battery="subItem.battery" :inline="subItem.inline"
									class="surplus margin-left-sm"></surplus>
							</view>
							<view class="text-center margin-top-xs">
								<img v-if="subItem.inline === 1" style="width:50rpx;height:50rpx;"
									src="../../assets/images/onLineLamp.png" alt="" mode="widthFix">
								<img v-else style="width:50rpx;height:50rpx;" src="../../assets/images/offLamp.png"
									alt="" mode="widthFix">
							</view>
						</view>
					</view>
				</view>
			</view>
			<view style="padding-bottom:150rpx;"></view>
		</mescroll-body>

		<view class="cu-modal bottom-modal" :class="[isShowControlModal?'show':'']" style="z-index:10001;">
			<view class="cu-dialog bg-white">
				<view class="bg-white padding text-df text-bold flex justify-between align-center">
					<view class="text-red-color">
						批量操作
					</view>
					<view class="flex align-center" @tap="deviceBatchCmd()">
						<view>历史记录</view>
						<view class="cuIcon-right padding-left"></view>
					</view>
				</view>
				<form>
					<view v-for="(item,index) in controllerList" :key="index"
						class="common-shadow padding-sm margin-xl flex justify-between align-center"
						@tap="selectOperate(item)">
						<view class="margin-left-sm flex justify-start align-center">
							<image style="width:40rpx;height:auto" :src="`${iconBaseUrl}${item.icon}`" mode="widthFix">
							</image>
							<view class="text-df padding-left-lg">{{item.name}}</view>
						</view>
						<view class="text-df flex justify-end align-center">
							<view v-if="item.displayModel==='time_interval'">
								<!-- time_interval -->
								<view class="flex justify-end align-center flex-wrap margin-bottom-sm ">
									<view class="flex-sub flex justify-center align-center setting-border padding-xs">
										<view class="">
											{{controllerMap[item.id] && Array.isArray(controllerMap[item.id]) ? controllerMap[item.id][0] : '开始时间'}}
										</view>
										<view class="margin-left-lg margin-right-lg text-center" style="width:10%;">
											<text class="text-df">至</text>
										</view>
										<view class="">
											{{controllerMap[item.id] && Array.isArray(controllerMap[item.id]) ? controllerMap[item.id][1] : '结束时间'}}
										</view>
									</view>
								</view>
							</view>
							<view v-if="item.displayModel==='control_ratio'">
								<!-- control_ratio -->
								<view class="flex justify-end flex-wrap">
									<view v-for="(param,paramIndex) in item.commandList" :key="paramIndex">
										<view v-if="param.value == controllerMap[item.id]">
											{{param.name}}
										</view>
									</view>
								</view>
							</view>
							<view v-if="item.displayModel==='control_slider'">
								<!-- control_slider -->
								<view class="">
									controllerMap[item.id]
								</view>
							</view>
							<view v-if="item.displayModel==='custom_btn'">
								<!-- custom_btn -->
								<view class="">
									{{controllerMap[item.id]}}
								</view>
							</view>
							<view v-if="item.displayModel==='display_time_switch'">
								<!-- display_time_switch -->
								<view class="flex justify-end align-center flex-wrap margin-bottom-sm ">
									<view class="">
										{{controllerMap['time' + item.id] ? controllerMap['time' + item.id] : '00:00:00'}}
									</view>
								</view>
							</view>
							<view v-if="item.displayModel != 'control_btn'" class="cuIcon-right padding-left-sm"></view>
						</view>
					</view>
					<button class="cu-btn bg-red block margin lg" @tap="isShowControlModal = false">
						关闭
					</button>
				</form>
			</view>
		</view>
		
		<view class="cu-modal bottom-modal" :class="[isDisplayModel?'show':'']" style="z-index:10001;">
			<view class="cu-dialog padding-bottom-lg bg-white">
				<view class="cu-bar bg-white">
					<view class="action text-bold">
						命令控制
					</view>
					<view class='action text-bold'>
						<view class="cuIcon-close text-grey" @tap="isDisplayModel = false"></view>
					</view>
				</view>
				<view class="margin" style="min-height: 20px;">
					<view v-for="(item,index) in currentControllerList" :key="index" class="">
						<view v-if="item.displayModel==='time_interval'">
							<!-- time_interval -->
							<view class="flex justify-end align-center flex-wrap margin-bottom-sm ">
								<view class="flex-sub flex justify-center align-center setting-border padding-xs">
									<picker :disabled="item.disabled" mode="multiSelector"
										:value="controllerMapTimeInterval[item.id] ? controllerMapTimeInterval[item.id].startTimeSlotMultiIndex : [0, 0, 0]"
										:range="startTimeSlotMultiArray"
										@change="startMultiCustomTimeSlotChange($event,item.id)">
										<view class="text-gray">
											{{controllerMap[item.id] && Array.isArray(controllerMap[item.id]) ? controllerMap[item.id][0] : '开始时间'}}
										</view>
									</picker>
									<view class="margin-left-lg margin-right-lg text-center" style="width:10%;">
										<text class="text-df">至</text>
									</view>
									<picker :disabled="item.disabled" mode="multiSelector"
										:value="controllerMapTimeInterval[item.id] ? controllerMapTimeInterval[item.id].endTimeSlotMultiIndex : [0, 0, 0]"
										:range="endTimeSlotMultiArray"
										@change="endMultiCustomTimeSlotChange($event,item.id)">
										<view class="text-gray">
											{{controllerMap[item.id] && Array.isArray(controllerMap[item.id]) ? controllerMap[item.id][1] : '结束时间'}}
										</view>
									</picker>
								</view>
								<button class="margin-lr-sm cu-btn block text-white" size="mini"
									:style="{backgroundColor: themeConfig.primaryColor}"
									@tap.stop="comfirmClick(item)">确定</button>
							</view>
						</view>
						<view v-if="item.displayModel==='control_ratio'">
							<!-- control_ratio -->
							<view class="flex justify-end flex-wrap">
								<button v-for="(param,paramIndex) in item.commandList" :key="paramIndex"
									class="margin-right-sm margin-bottom-sm cu-btn block" size="mini"
									:class="[param.value == controllerMap[item.id] ? 'selectButton' : 'unSelectButton']"
									:style="{'--color': themeConfig.primaryColor}"
									@tap.stop="comfirmClick(item,param.value)">{{param.name}}</button>
							</view>
						</view>
						<view v-if="item.displayModel==='control_slider'">
							<!-- control_slider -->
							<view class="flex justify-end flex-wrap">
								<input-number class="flex-sub" :number="controllerMap[item.id]" :item="item"
									:max="parseInt(item.valueEnd)" :min="parseInt(item.valueStart)"
									@changeNumber="changeNumber"></input-number>
								<button class="margin-lr-sm margin-bottom-sm cu-btn block text-white" size="mini"
									:style="{backgroundColor: themeConfig.primaryColor}"
									@tap.stop="comfirmClick(item)">确定</button>
							</view>
						</view>
						<view v-if="item.displayModel==='custom_btn'">
							<!-- custom_btn -->
							<view class="flex justify-end flex-wrap">
								<input v-model="controllerMap[item.id]" type="text"
									class="margin-right-sm flex-sub setting-border text-center setting-input" />
								<button class="margin-right-sm margin-bottom-sm cu-btn block text-white" size="mini"
									:style="{backgroundColor: themeConfig.primaryColor}"
									@tap.stop="comfirmClick(item)">确定</button>
							</view>
						</view>
						<view v-if="item.displayModel==='display_time_switch'">
							<!-- display_time_switch -->
							<view class="flex justify-end align-center flex-wrap margin-bottom-sm ">
								<view
									class="flex-sub flex justify-center align-center setting-border padding-xs margin-right-sm">
									<picker :disabled="item.disabled" mode="multiSelector"
										:value="controllerMapTimeInterval[item.id] ? controllerMapTimeInterval[item.id].timeSlotMultiIndex : [0, 0, 0]"
										:range="timeSlotMultiArray" @change="multiCustomTimeSlotChange($event,item)">
										<view class="text-gray">
											{{controllerMap['time' + item.id] ? controllerMap['time' + item.id] : '00:00:00'}}
										</view>
									</picker>
								</view>
								<button v-for="(param,paramIndex) in item.commandList" :key="paramIndex"
									class="margin-right-sm cu-btn block" size="mini"
									:class="[param.value == controllerMap[item.id] ? 'selectButton' : 'noSelectButton']"
									:style="{'--color': themeConfig.primaryColor}"
									@tap.stop="comfirmClick(item,param.value)">{{param.name}}</button>
							</view>
							<view class="item-desc">
								<view class="countdown" v-if="item.running&&durations[item.id]>0">
									倒计时：{{returnHMS(durations[item.id])}}
									<view class="count-style">
										<view class="count-style-inner"
											:style="{'width':(durations[item.id]/parseInt(item.durationTotal))*100+'%','--color': themeConfig.primaryColor}">
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="cu-modal bottom-modal" :class="[isShowCmdModal?'show':'']"
			style="text-align: start;z-index:10001;">
			<view class="cu-dialog bg-white">
				<view class="cu-bar bg-white">
					<view class="action text-bold">
						命令记录
					</view>
					<view class='action text-bold'>
						<view class="cuIcon-close text-grey" @tap="isShowCmdModal = false"></view>
					</view>
				</view>
				<form>
					<view class="cu-form-group" @tap="deviceBatchCmdLog(cmdData)">
						<view class="bg-white light common-box text-sm margin padding" style="width: 100%;">
							<view class="flex justify-between padding-bottom-sm"
								style="border-bottom:1px solid rgba(0, 0, 0, 0.1);">
								<view class="text-content">
									<text class="margin-right-sm">执行命令:</text>
									<text>{{cmdData.name}}</text>
								</view>
							</view>
							<view class="margin-top-sm text-df">
								<text class="margin-right-xs ">项目名称:</text>
								<text class="text-gray">{{cmdData.associationName}}</text>
							</view>
							<view class="margin-top-sm text-df">
								<text class="margin-right-xs ">执行类型:</text>
								<text :style="[{color:themeConfig.primaryColor}]">{{cmdData.batchType}}</text>
							</view>
							<view class="margin-top-sm text-df">
								<text class="margin-right-xs ">开始时间:</text>
								<text class="text-gray">{{cmdData.startTime}}</text>
							</view>
							<view class="margin-top-sm text-df">
								<text class="margin-right-xs">完成时间:</text>
								<text class="text-yellow">{{cmdData.finishTime}}</text>
							</view>
							<view class="margin-top-sm text-df">
								<text class="margin-right-xs ">执行设备数:</text>
								<text class="text-gray">{{cmdData.execCount}}</text>
							</view>
							<view class="margin-top-sm text-df">
								<text class="margin-right-xs">执行成功数:</text>
								<text class="text-yellow">{{cmdData.successCount}}</text>
							</view>
							<view class="margin-top-sm text-df">
								<text class="margin-right-xs">执行失败数:</text>
								<text class="text-yellow">{{cmdData.failCount}}</text>
							</view>
							<view class="margin-top-sm text-df">
								<text class="margin-right-xs">执行状态:</text>
								<text class="text-yellow">{{cmdData.status}}</text>
							</view>
						</view>
					</view>
					<button class="cu-btn bg-red block margin lg" @tap="deviceBatchCmdLog(cmdData)">
						查看
					</button>
				</form>
			</view>
		</view>

		<view style="position:fixed;bottom:0;z-index:1;">
			<view class="flex justify-between align-center padding-xl bg-white" style="width:100vw;">
				<button class="cu-btn lg bg-red-color text-white" style="width:45vw;border-radius:8rpx;font-size:28rpx;"
					@tap="deleteInsecticidalLampProject">删除项目组</button>
				<button class="cu-btn lg bg-blue-color text-white margin-left"
					style="width:45vw;border-radius:8rpx;font-size: 28rpx;"
					@tap="isShowControlModal = true">批量操作</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		showModal,
		showToast,
		showLoading,
		hideLoading
	} from '@/util/toast'
	import myConfig from '@/myConfig'
	import * as ztIotApi from '@/api/dmIot/ztIotApi.ts'
	import Surplus from '@/components/ztn-custom/Surplus2'
	import Signal from '@/components/ztn-custom/Signal'
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins';
	export default {
		name: 'manageDevice',
		mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
		components: {
			Surplus,
			Signal
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		data() {
			return {
				isLogin: false,
				downOption: {
					use: true,
					auto: false, //是否在初始化后,自动执行downCallback; 默认true
					native: false
				},
				upOption: {
					use: true,
					auto: false,
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					empty: {
						use: true,
						fixed: true,
						top: '25%'
					},
				},
				iconBaseUrl: myConfig.app.iconBaseUrl,
				currentPage: 1,
				pageSize: 999,
				lastPage: -1,
				lastIndex: -1,
				total: -1,
				deviceList: [],
				projectId: "",
				projectName: "",
				focus: false,
				selectDevice: null,
				isShowControlModal: false,
				isDisplayModel: false,
				currentControllerList: [],
				controllerList: [],
				controllerMap: {},
				controllerMapTimeInterval: {},
				isShowCmdModal: false,
				cmdData: {},
			}
		},
		onLoad(option) {
			this.projectId = option.id
			this.projectName = option.name
			this.getDeviceList()
			this.getIndexControl()
		},
		onShow() {
			uni.$once("refreshAddDevice", () => {
				let bool = true
				if (bool) {
					this.refresh()
					uni.$emit("navChange", "project")
					bool = false
				}
			})
		},
		methods: {
			refresh() {
				this.deviceList = []
				this.getDeviceList()
			},
			downCallback() {
				this.currentPage = 1
				this.deviceList = []
				this.mescroll.resetUpScroll()
			},
			getIndexControl() {
				let projectId = this.projectId
				ztIotApi.getIndexControl({
					projectId
				}).then((res) => {
					let {
						msg,
						data,
						success
					} = res
					let controllerList = []
					this.controllerMap = {};
					this.controllerMapTimeInterval = {};
					for (let i = 0; i < data.length; i++) {
						let item = data[i]
						let params = {}
						if (item.displayModel === 'time_interval') {
							this.$set(this.controllerMapTimeInterval, item.id, {
								startTimeSlotMultiIndex: [0, 0, 0],
								endTimeSlotMultiIndex: [0, 0, 0]
							})
						}
						if (item.cmdValue && typeof(item.cmdValue) === 'string') {
							params = JSON.parse(item.cmdValue)
							if (params.value1 && !params.value2) {
								this.$set(this.controllerMap, item.id, params.value1)
							} else if (params.value1 && params.value2) {
								this.$set(this.controllerMap, item.id, [params.value1, params
									.value2
								])
							}
						}
						if (item.displayModel === 'display_time_switch') {
							if (params.time) {
								let hms = params.time.split(':')
								let date = new Date();
								let year = date.getFullYear();
								let month = date.getMonth() + 1;
								let day = date.getDate();
								let hour = parseInt(hms[0]);
								let min = parseInt(hms[1]);
								let second = parseInt(hms[2]);
								this.$set(this.controllerMap, ('time' + item.id), params.time)
								this.$set(this.controllerMapTimeInterval, item.id, {
									timeSlotMultiIndex: [hour, min, second],
								})
							}
						}
						controllerList.push(item)
					}
					this.controllerList = controllerList
				})
			},
			selectOperate(item) {
				this.isShowControlModal = false
				this.currentControllerList = [item]
				if (item.displayModel !== 'control_btn') {
					//control_btn 按钮
					this.isDisplayModel = true
				} else {
					//其他
					this.isDisplayModel = false
					this.comfirmClick(item)
				}
			},
			comfirmClick(item, value) {
				if (item.running) {
					showToast("当前正在操作", "none", 2000, false)
					return;
				}
				showLoading(this.$t('loading'), true)
				this.comfirmIng = true
				let params = {
					cmdFlag: item.cmdFlag,
					projectId: this.projectId,
					param: {}, // 时间区间2个值，其他目前1个值
					type: 1
				}
				if (item.displayModel === 'time_interval') {
					//time_interval 时间区间
					if (this.controllerMap[item.id] && this.controllerMap[item.id].length === 2) {
						// console.log(this.controllerMap[item.id])
						params.param.value1 = this.controllerMap[item.id][0]
						params.param.value2 = this.controllerMap[item.id][1]
					} else {
						this.$message.error("请选择时间区间");
						return
					}
				} else if (item.displayModel === 'control_ratio') {
					//control_ratio 单选
					this.$set(this.controllerMap, item.id, value)
					params.param.value1 = this.controllerMap[item.id]
				} else if (item.displayModel === 'control_slider') {
					//control_slider 滑块
					params.param.value1 = this.controllerMap[item.id]
				} else if (item.displayModel === 'control_btn') {
					//control_btn 按钮
					params.param = {};
				} else if (item.displayModel === 'custom_btn') {
					//custom_btn 输入框
					if (!this.controllerMap[item.id]) {
						showToast("请输入内容", "none", 2000, false)
					}
					params.param.value1 = this.controllerMap[item.id]
				} else if (item.displayModel === 'display_time_switch') {
					//倒计时
					if (!this.controllerMap['time' + item.id]) {
						this.$message.error("请选择执行时长");
						return
					}
					this.$set(this.controllerMap, item.id, value)
					params.param.time = this.controllerMap['time' + item.id]
					params.param.value1 = this.controllerMap[item.id]
				}
				setTimeout(()=>{
					hideLoading()
				},1000)
				this.handleCommit(params)
			},
			handleCommit(params) {
				ztIotApi.commandInsecticidalLampDevice(params).then(res => {
					if (res.success) {
						showToast("操作成功！", "none", 2000, false)
						this.isShowCmdModal = true
						this.cmdData = res.data.cmd
					}
					setTimeout(() => {
						this.getIndexControl()
						this.isDisplayModel = false
					}, 0)
				})
			},
			getDeviceList() {
				let currentPage = this.currentPage
				let pageSize = this.pageSize
				let projectId = this.projectId
				let params = {
					pageNum: currentPage,
					pageSize,
					projectId,
				}
				ztIotApi.getInsecticidalLampDeviceList(params).then((res) => {
					const {
						code,
						msg,
						rows,
						total
					} = res
					const lastPage = Math.ceil(total / pageSize)
					const lastIndex = total % pageSize
					const index = currentPage - 1
					this.mescroll.endSuccess(rows.length, currentPage < lastPage)
					this.$set(this.deviceList, index, rows)
					this.lastPage = lastPage
					this.lastIndex = lastIndex
					this.total = total
					if (currentPage < lastPage) {
						this.currentPage = currentPage + 1
					}
				})
			},
			changeFocus() {
				this.focus = true
			},
			updateInsecticidalLampProject() {
				let projectId = this.projectId
				let projectName = this.projectName
				let params = {
					id: projectId,
					name: projectName
				}
				ztIotApi.updateInsecticidalLampProject(params).then((res) => {
					let {
						code,
						msg,
						success,
					} = res
					if (success) {
						uni.$emit("navChange", "project")
						showToast("操作成功", 'none', 1000, false) //操作成功
					}
				})
			},
			remProjectDevice(item) {
				const title = '解除绑定'
				const content = '确认' + '解除绑定' + '?'
				const confirmText = '确认'
				const cancelText = '取消'
				showModal(title, content, true, confirmText, cancelText, () => {
					const projectId = this.projectId
					const params = {
						id: projectId,
						deviceId: item.id
					}
					ztIotApi.remProjectDevice(params).then((res) => {
						let {
							code,
							msg,
							success,
						} = res
						if (success) {
							this.refresh()
							uni.$emit("navChange", "project")
							showToast('操作成功', 'success', 1000, false)
						}
					})
				}, () => {
					return
				})
			},
			deleteInsecticidalLampProject() {
				let projectId = this.projectId
				let params = {
					id: projectId
				}
				ztIotApi.deleteInsecticidalLampProject(params).then((res) => {
					let {
						code,
						msg,
						success,
					} = res
					if (success) {
						uni.$emit("navChange", "project")
						showToast("操作成功", 'none', 1000, false) //操作成功
						this.backPage()
					}
				})
			},
			backPage() {
				uni.navigateBack({
					delta: 1
				});
			},
			deviceBatchCmd() {
				uni.navigateTo({
					url: `/pages/deviceBatchCmd/deviceBatchCmd`
				})
			},
			deviceBatchCmdLog(item) {
				uni.navigateTo({
					url: `/pages/deviceBatchCmdLog/deviceBatchCmdLog?id=${item.id}`
				})
			},
			goToAddDevice(id) {
				uni.navigateTo({
					url: `/pages/addDevice/addDevice?id=${id}`
				})
			},
			deviceInfo(item) {
				uni.navigateTo({
					url: `/pages/deviceInfo/deviceInfo?id=${item.id}&code=${item.code}`
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.text-gray-color {
		color: #cdcdcd;
	}

	.text-red-color {
		color: #ff0000;
	}

	.bg-red-color {
		background-color: #f33423;
	}

	.bg-blue-color {
		background-color: #3d5dd2;
	}

	.common-shadow {
		box-shadow: 0upx 0upx 10upx 4upx rgba(0, 0, 0, 0.1);
		border-radius: 8px;
	}
	
	.selectButton {
		color: #fff;
		background-image: linear-gradient(to bottom right, #ff5b62, #ff0202);
	}
	
	.unSelectButton {
		color: #8799a3;
		background-color: #efefef
	}
</style>
